package com.kindness.frate.http;

import com.kindness.frate.http.model.UserInfo;
import com.kindnesslibrary.network.retrofit.RetrofitManager;

import java.io.File;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Api接口
 */
public class ApiWrapper {

    final Observable.Transformer transformer = new Observable.Transformer() {
        @Override
        public Object call(Object observable) {
            return ((Observable) observable)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .flatMap(new Func1() {
                        @Override
                        public Object call(Object response) {
                            return flatResponse((Response<Object>) response);
                        }
                    });
        }
    };

    /**
     * 对网络接口返回的Response进行分割操作
     *
     * @param response
     * @param <T>
     * @return
     */
    public <T> Observable<T> flatResponse(final Response<T> response) {
        return Observable.create(new Observable.OnSubscribe<T>() {

            @Override
            public void call(Subscriber<? super T> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    if(response.result != null) {
                        subscriber.onNext(response.result);
                    }else{
                        subscriber.onNext(response.results);
                    }
                }
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onCompleted();
                }
            }
        });
    }


    /**
     * Transformer实际上就是一个Func1<Observable<T>, Observable<R>>，
     * 换言之就是：可以通过它将一种类型的Observable转换成另一种类型的Observable，
     * 和调用一系列的内联操作符是一模一样的。
     */
    protected <T> Observable.Transformer<Response<T>, T> applySchedulers() {
        return (Observable.Transformer<Response<T>, T>) transformer;
    }

    /**
     * 登录
     * @param userInfo
     * @return
     */
    public Observable<UserInfo> login(UserInfo userInfo){
        return RetrofitManager.getInstance().getApiService(ApiService.class).login(userInfo).compose(this.<UserInfo>applySchedulers());
    }

    /**
     * 登录
     * @param uploadFile 将要上传的文件
     * @return
     */
    public Observable<String> uploadFile(File uploadFile){
        return RetrofitManager.getInstance().getApiService(ApiService.class).uploadFile(uploadFile).compose(this.<String>applySchedulers());
    }
}
